/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.web.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.guoyu.project.common.utils.PropertyUtil;
import com.guoyu.project.service.FileUploadService;

/**
 * @author: libo Date: 17-5-24 Time: 下午3:08
 * @version: \$Id$
 */
@Controller
@RequestMapping("admin/wang")
public class EditorUploadController {

    @Resource
    private FileUploadService fileUploadService;

    private String domain = PropertyUtil.getProperty("domain");

    @RequestMapping("upload")
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        PrintWriter out = response.getWriter();

        if (!multipartResolver.isMultipart(request)) {
            out.print("error|文件上传请求错误");
        }

        // 转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        // 取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();

        String filePath = "";
        while (iter.hasNext()) {
            // 取得上传文件
            MultipartFile file = multiRequest.getFile(iter.next());
            filePath = fileUploadService.upload(file);
        }
        response.getWriter().print(domain + filePath);
    }
}
